<template>
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="职位搜索:" prop="">
                <el-input placeholder="请输入搜索职位关键字" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item label="" prop="">
                <el-button type="primary" :disabled="keyword ? false : true" @click="search">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
        <el-button type="primary" icon="Plus" @click="addRole">添加职位</el-button>
        <el-table border style="margin: 10px 0;" :data="roleArr">
            <el-table-column label="#" align="center" type="index"></el-table-column>
            <el-table-column label="id" align="center" prop="id"></el-table-column>
            <el-table-column label="职位名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row, $index }">
                    <el-button type="primary" @click="setPermission(row)" icon="User" size="small">分配权限</el-button>
                    <el-button type="primary" @click="updateRole(row)" icon="Edit" size="small">编辑</el-button>
                    <el-popconfirm :title="`你确定要删除${row.roleName}吗？`" width="250px" @confirm="removeRole(row.id)">
                        <template #reference>
                            <el-button type="primary" @click="" icon="Delete" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
            :background="true" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
            @current-change="getHasRole" @size-change="handler" />
    </el-card>
    <el-dialog v-model="dialogVisit" :title="RoleParams.id ? '更新职位' : '添加职位'">
        <el-form :model="RoleParams" :rules="rules" ref="formRole">
            <el-form-item label="职位名称" prop="roleName">
                <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="cancel">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
        </template>
    </el-dialog>
    <el-drawer v-model="drawer">
        <template #header>
            <h4>分配菜单与按钮的权限</h4>
        </template>
        <template #default>
            <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="selectArr" :props="defaultProps" />
        </template>
        <template #footer>
            <el-button type="" @click="drawer = false"> 取消</el-button>
            <el-button type="primary" @click="handler2">确定</el-button>
        </template>
    </el-drawer>
</template>

<script setup lang='ts' name="Role">
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqAllRole, reqAddRoleOrUpdate, reqAllPermission, reqSetPermission, reqDeleteRole } from '@/api/acl/role/index'
import type { RoleResponseData, records, Records, MenuResponseData, MenuList } from '@/api/acl/role/type'
import useLayOutSettingStore from '@/store/modules/setting';
import { ElMessage } from 'element-plus';
let LayOutSettingStore = useLayOutSettingStore()
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let roleArr = ref<records>([])
let keyword = ref<string>('')
let dialogVisit = ref<boolean>(false)
let formRole = ref<any>()
let drawer = ref<boolean>(false)
let menuArr = ref<MenuList>([])
let RoleParams = reactive<Records>({
    roleName: ''
})
//准备数组，用于存储勾选的节点的id
let selectArr = ref<any>([])
let tree = ref<any>()
const defaultProps = {
    children: 'children',
    label: 'name',
}
onMounted(() => {
    getHasRole()
})
const getHasRole = async (pager = 1) => {
    pageNo.value = pager
    let result: RoleResponseData = await reqAllRole(pageNo.value, pageSize.value)
    if (result.code == 200) {
        total.value = result.data.total
        roleArr.value = result.data.records
    }
}
const handler = () => {
    getHasRole()
}
//搜索
const search = () => {
    getHasRole()
    keyword.value = ''
}
//重置
const reset = () => {
    LayOutSettingStore.refsh = !LayOutSettingStore.refsh
}
const addRole = () => {
    dialogVisit.value = true
    Object.assign(RoleParams, {
        roleName: ''
    })
    nextTick(() => {
        formRole.value.clearValidate('roleName')
    })
}
const updateRole = (row: Records) => {
    dialogVisit.value = true
    Object.assign(RoleParams, row)
    nextTick(() => {
        formRole.value.clearValidate('roleName')
    })
}
const cancel = () => {
    dialogVisit.value = false
}
const validatorRoleName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 2) {
        callback()
    } else {
        callback(new Error('职位名称至少两位'))
    }
}
const rules = {
    roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }]
}
const save = async () => {
    await formRole.value.validate()
    let result: any = await reqAddRoleOrUpdate(RoleParams)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: RoleParams.id ? '更新成功 ' : '添加成功' })
        dialogVisit.value = false
        getHasRole(RoleParams.id ? pageNo.value : 1)

    }
}
//分配权限按钮
const setPermission = async (row: Records) => {
    drawer.value = true
    Object.assign(RoleParams, row)
    //根据职位获取权限的数据
    let result: MenuResponseData = await reqAllPermission((RoleParams.id as number))
    if (result.code == 200) {
        menuArr.value = result.data
        selectArr.value = filterSelectarr(menuArr.value, [])
    }
}
const filterSelectarr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if (item.select && item.level == 4) {
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelectarr(item.children, initArr)
        }
    });
    return initArr
}
const handler2 = async () => {
    const roleId = (RoleParams.id as number)
    let arr = tree.value.getCheckedKeys();
    let arr1 = tree.value.getHalfCheckedKeys();
    let permissionId = arr.concat(arr1)
    let result: any = await reqSetPermission(roleId, permissionId)
    if (result.code == 200) {
        drawer.value = false
        ElMessage({ type: 'success', message: '分配权限成功' })
        window.location.reload()
    }
}
const removeRole = async (roleId: number) => {
    let result: any = await reqDeleteRole(roleId)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasRole(roleArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}
</script>
<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>